package com.zsj.juc.threadlocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/5/19 16:16
 * @description 线程池问题
 */
class Resource {
    public ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public void add() {
        threadLocal.set(threadLocal.get() + 1);
    }
}

public class ThreadPoolLocalQuestionDemo {

    public static void main(String[] args){
        /*
        能看到线程池中的每个线程会被复用
        如果不对这个线程中的数据进行remove的话
        会造成数据越来越大
        所以我们每次使用 要记得清除

        WeakReference  弱引用

        ThreadLocal中使用的是ThreadLocalMap进行元素的读写
        ThreadLocalMap  entry对象 实际里面存到就是一个threadLocal为key  任意对象为value的对象
         */
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Resource resource = new Resource();
        try {
            for (int i = 0; i < 6; i++) {
                executorService.submit(() -> {
                    try {

                        Integer before = resource.threadLocal.get();
                        resource.add();
                        Integer after = resource.threadLocal.get();
                        System.out.println(Thread.currentThread().getName() + ": " + before + "->" + after);
                    } finally {
                        resource.threadLocal.remove();
                    }
                });
            }
        } finally {
            executorService.shutdown();
        }

    }
}
